<!DOCTYPE HTML>
<html>

<head>
<meta charset="UTF-8">
<title>html5websock.html</title>

<script type="text/javascript" language="Javascript" 
        src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
		
		
<script>
var connection;// = new WebSocket('wss://push.planetside2.com/streaming?service-id=s:rch');
var ratch_id = '';//'5428010618043506641';
var user_id = '';
var user_name = '';
var player_arr = [];
var counter = '99';

function Info (type) {
	this.id = '';
	this.name = '';
	this.kills = 0;// times killed you
	this.deaths = 0;// times killed by you
}

Info.prototype.getInfo = function() {
	var _n = '<td style="width:10em"' + ' id="'+this.id + '_n">' + this.name + '</td>';
	var _k = '<td style="width:3em"' + ' id="'+this.id + '_k">' + this.kills + '</td>';
	var _d = '<td style="width:3em"' + ' id="'+this.id + '_d">' + this.deaths + '</td>';
	var _h = '<td style="width:30em"' + ' id="'+this.id + '_h"></td>';
    return _n + _k + _d + _h;
};

Info.prototype.updateKD = function() {
	$("#" + this.id + "_k").text( this.kills );
	$("#" + this.id + "_d").text( this.deaths );
};

Info.prototype.addHistory = function(h) {
	var idt = this.id + '_h';
	$("#" + idt).text( $("#" + idt).text() + h );
	console.log("RCH addHistory:" + $("#" + idt).html() );
};

// Button for testing / debug		
$(document).ready(function(){
	//player_name_field

	$("#ratch_init").click(function() {
		startup( 'ratch' );
	});

	$("#init_button").click(function() {
		startup( $("#player_name_field").val() );
	});

	$("#button1").click(function() {
		addPlayer('12341234123412341324', 'noob5000');
	});
	
	$("#button2").click(function() {
		 playerKill( addPlayer(ratch_id, user_name) );
		 playerDeath( addPlayer(ratch_id, user_name) );
		 getKillData(null, user_name, user_name);
	});
	
	$("#button3").click(function() {
		 playerKill( addPlayer(counter++, counter++) );
		 getKillData(null, counter, user_name);
	});
	
	$("#button4").click(function() {
		 playerDeath( addPlayer(counter++, counter++) );
		 getKillData(null, user_name, counter);
	});
	
	$("#button5").click(function() {
		var ind = Math.floor( Math.random() * player_arr.length );
		console.log("BUTTON5 ind=", ind);
		playerDeath( addPlayer(player_arr[ind].id, player_arr[ind].name) );
		getKillData(null, player_arr[ind].name, user_name);
	});
});
// ************ STARTUP ********************
function startup(player_name) {
	$.ajax({ 
	   type: "GET",
	   dataType: "jsonp",
	   url: 'http://census.soe.com/get/ps2/character/?name.first_lower=' + player_name,//'http://census.soe.com/s:rch/get/ps2:v2/character/?character_id=' + victim + '&c:show=name',
	   success: function(data){
		 console.log("RCH startup():", data);
		 init( data.character_list[0].character_id, player_name);
	   }
	});
}

function init(player_id, player_name) {
	console.log("RCH init " );
	//user_id = player_id;
	ratch_id = player_id;
	user_name = player_name;
	connection = new WebSocket('wss://push.planetside2.com/streaming?service-id=s:rch');
	
	/////////////////////start connection define
	// When the connection is open, send some data to the server
	connection.onopen = function () {
	  //connection.send('Ping'); // Send the kill_stream 'Ping' to the server
	  var kill_events = '{"service":"event","action":"subscribe","characters":["' + ratch_id + '"],"eventNames":["Death"]}';
	  connection.send(kill_events);
	  console.log("RCH connection opened");
	  
	};

	// Log errors
	connection.onerror = function (error) {
	  console.log('WebSocket Error ' + error);
	};

	// Log kill_streams from the server
	connection.onmessage = function (e) {
	  var msg = jQuery.parseJSON( e.data );
	  if( msg.type != 'serviceStateChanged' ) {
		console.log("msg:", msg);
	  }
	  
	  
		if( msg.service == 'event' && msg.type == 'serviceMessage' ) {
			var attacker = msg.payload.attacker_character_id;
			var victim = msg.payload.character_id;
			
			if (attacker == ratch_id) {// ratch kill!
				$.ajax({ 
				   type: "GET",
				   dataType: "jsonp",
				   url: 'http://census.soe.com/s:rch/get/ps2:v2/character/?character_id=' + victim + '&c:show=name',
				   success: function(data){
					 console.log("RCH success()1:", data);
					 playerDeath( addPlayer(victim, data.character_list[0].name.first) );
					 getKillData(data, user_name, data.character_list[0].name.first);
				   }
				});
				
			} else if (victim == ratch_id) {//ratch died...
				$.ajax({ 
				   type: "GET",
				   dataType: "jsonp",
				   url: 'http://census.soe.com/s:rch/get/ps2:v2/character/?character_id=' + attacker + '&c:show=name',
				   success: function(data){
					 console.log("RCH success()2:", data);
					 playerKill( addPlayer(attacker, data.character_list[0].name.first) );
					 getKillData(data,  data.character_list[0].name.first, user_name);
				   }
				});
				
			}
		}
		/**/
	};// end connection.onmessage
	///////end connection define
}//end init

function addPlayer(player_id, player_name) {
	//console.log("RCH addPlayer(", player_id, ", ", player_name, ")");
	ind = playerIndex(player_id);
	//console.log("RCH addPlayer() ind:", ind);
	if( ind < 0 ) {
		p = new Info();// add player
		p.id = player_id;
		p.name = player_name;
		ind = player_arr.length;
		player_arr.push( p );
		//$("#player_cache").html( player_name + '<br />' + $("#player_cache").html());
		//$('#player_cache tr:last').after('<tr id="' + player_id + '_tr">' + p.getInfo + '</tr>');
		$('#player_cache').append('<tr id="' + player_id + '_r">' + p.getInfo() + '</tr>');
		
		//console.log("RCH cache:" + $('#player_cache').html() );
	}
	return ind;
}

function playerDeath(ind) {
	player_arr[ind].deaths++;
	player_arr[ind].addHistory("D");
	player_arr[ind].updateKD();
}

function playerKill(ind) {
	player_arr[ind].kills++;
	player_arr[ind].addHistory("K");
	player_arr[ind].updateKD();
}

function playerIndex(player_id) {
	var found = -1;
	for( var i = 0; i < player_arr.length; i++ ) {
		//console.log("FOR" + i + " player_arr[i].id=", player_arr[i].id, "RCH player_id=", player_id);
		if ( player_arr[i].id == player_id ) {
			found = i;
			break;
		}
	}
	return found;
}
  
function getKillData(data, attacker, victim) {// data not used
	console.log('RCH getKillData() attacker:', attacker, ' victim:', victim); 
	if (attacker == victim) {//suicide
		$("#kill_stream").html( '<hr><i>'+attacker+' committed suicide...</i><br />' + $("#kill_stream").html());
	} else 	if( attacker == user_name ) {
		$("#kill_stream").html( '<strong>&nbsp;'+attacker+' killed '+victim+'</strong><br />' + $("#kill_stream").html());
	} else {
		$("#kill_stream").html( '-<br />' + attacker + ' killed '+victim+'<br />' + $("#kill_stream").html());
	}
}

// check connection status
setInterval(function(){
	if (connection != null) {
		switch(connection.readyState) {
			case 0:
				$("#con_status").val(connection.readyState+': connection not yet established');
			break;
			case 1:
				$("#con_status").val(connection.readyState+': conncetion established');
			break;
			case 2:
				$("#con_status").val(connection.readyState+': in closing handshake');
			break;
			case 3:
				$("#con_status").val(connection.readyState+': connection closed or could not open');
			break;
	}
},1000);

  
</script>
</head>

<body>

<script>
</script>

Enter your Player Name:<input id='player_name_field' type="text" name="player_name">
Connection Status:<input type="text" id="con_status" rows="1" cols="20" readonly>
<button id="init_button">Lets do this!</button><button id="ratch_init">Ratch INIT!</button><br />


<button id="button1">button1</button><button id="button2">suicide</button><button id="button3">new rand kill ratch</button><button id="button4">ratch kill</button>
<button id="button5">rand kill ratch</button>
 <!---->
<p id="testp"></p>

<table style="width:1000px; border: 1px solid black;">
	<th>Kill Feed</th>
	<th>Players Involved</th>
	<tr>
		<td style="border: 1px solid black; width:30%"><p id="kill_stream"></p></td>
		<td valign="top"; style="border: 1px solid black;">
			<table id="player_cache" style="border: 1px solid black;">
				<tr valign="bottom">
					<th style="width:10em">Player Name</th>
					<th style="width:3em">Kills</th>
					<th style="width:3em">Deaths</th>
					<th style="width:30em">Events Feed <!--<br />(D= You killed this player,<br /> K= This player killed you.)--></th>
				</tr>
			</table>
		</td>		
	</tr>
</table>



</body>
</html>














